<template>
  <van-nav-bar :title="goodsData.goods.title" :fixed="true" left-arrow @click-left="router.back()"/>
  <van-image
    width="100%"
    fit="cover"
    :src="goodsData.goods.cover_url"
    class="mt46"
  />
  <div class="goodsInfo">
    <h1 class="goodsTitle">{{goodsData.goods.title}}</h1>
    <!-- 商品信息卡片 -->
    <van-card
      :desc="goodsData.goods.description"
    >
      <template #tags>
        <van-tag plain type="danger">新书</van-tag>
        <van-tag plain type="danger">推荐</van-tag>
        <van-tag plain type="danger">特价</van-tag>
        <van-tag plain type="danger">节日活动</van-tag>
      </template>
      <template #price>
        <span><small>&yen;</small>{{goodsData.goods.price}}.00</span>
      </template>
      <template #num>
        <span>剩余{{goodsData.goods.stock}}件</span>
      </template>
      <template #bottom>
        <div class="count">
          <span>数量：</span>
          <van-stepper v-model="store.count" :max="goodsData.goods.stock"/>
        </div>
      </template>
      <template #footer>
        <div class="collect" @click="handlecollect">
          <van-icon :name="goodsData.goods.is_collect === 0 ? 'star-o' : 'star'" />
          <span v-if="goodsData.goods.is_collect === 0">收藏</span>
          <span v-if="goodsData.goods.is_collect === 1">已收藏</span>
        </div>
        <button class="cartBtn" @click="handleJoinCart">加入购物车</button>
        <button class="buyBtn" @click="handleBuyNow">立即购买</button>
      </template>
    </van-card>
  </div>
  <!-- tabs选项 -->
  <van-tabs v-model:active="goodsData.active">
    <van-tab title="概述">
      <div v-html="goodsData.goods.details"></div>
    </van-tab>
    <van-tab title="热评">
      <van-empty description="评论功能尚未开放!" />
    </van-tab>
    <van-tab title="相关图书">
      <van-grid :column-num="2">
        <van-grid-item
          v-for="likeItem in goodsData.like_goods"
          :key="likeItem.id"
          class="item"
          @click="goToDetail(likeItem.id)"
          >
          <van-image :src="likeItem.cover_url" />
          <div class="info">
            <p>{{ likeItem.title }}</p>
            <p>
              <span>&yen;&nbsp;{{ likeItem.price }}</span>
              <span><van-icon name="star-o" />{{likeItem.collects_count}}</span>
            </p>
          </div>
        </van-grid-item>
      </van-grid>
    </van-tab>
</van-tabs>
</template>
    
<script setup lang='ts'>
import { detail,collect } from '@/api/goods'
import { addCart } from '@/api/cart'
import { onMounted, reactive, ref, toRefs, watch } from 'vue';
import { InitGoodsData } from '@/types/goods'
import { useRoute,useRouter } from 'vue-router';
import { Toast } from 'vant';
import { useGoodsStore } from '@/store/goods'

  const route = useRoute()
  const router = useRouter()
  let store = useGoodsStore()
  let goodsId = Number(route.params.id)
  const goodsData = reactive(new InitGoodsData())
  // 点购商品数量
  // let count = ref<number>(0)
  
  
  const getDetailData = async () => {
    let res = await detail(goodsId)
    if(res.status === 200){
      goodsData.goods = res.data.goods
      goodsData.like_goods = res.data.like_goods
    }
  }
  // 登录校验
  const loginRule = () => {
    let token = localStorage.getItem("bookshop-token")
    if(!token){
      Toast.fail("请先登录!")
      router.push('/login')
      return
    }
  }
  // 收藏
  const handlecollect = async () => {
    loginRule()
    let res = await collect(goodsId)
    if(res.status === 201){
      goodsData.goods.is_collect = 1
      Toast.success("收藏成功!")
    }else if(res.status === 204){
      goodsData.goods.is_collect = 0
      Toast("取消收藏!")
    }
  }
  // 加入购物车
  const handleJoinCart = async () => {
    loginRule()
    let list = {
      goods_id:goodsId,
      num:store.count
    }
    let res = await addCart(list)
    if(res.status === 204 || res.status === 201){
      Toast.success("添加成功!")
      store.resetCount()
      router.push('/cart')
    }else{
      Toast.fail("添加失败，请联系商家")
    }
  }
  // 立即购买
  const handleBuyNow = async () => {
    loginRule()
    let list = {
      goods_id:goodsId,
      num:store.count
    }
    let res = await addCart(list)
    if(res.status === 204 || res.status === 201){
      router.push('/cart')
      store.resetCount()
    }else{
      Toast.fail("购买失败，请联系客服")
    }
  }
  // 跳转商品详情页
  const goToDetail = (id:number) => {
    router.push({name: "detail",params:{id}})
  }
  // 侦听路由变化
  watch(() => router.currentRoute,(newVal,oldVal) => {
    goodsId = Number(newVal.value.params.id)
    getDetailData()
    router.go(0)
  },{deep:true})

  onMounted(() => {
    getDetailData()
    
  })
</script>
    
<style scoped lang="less">
.goodsInfo {
  .goodsTitle {
    font-size: 18px;
    font-weight: 700;
    color: #fff;
    width: 100%;
    height: 30px;
    line-height: 30px;
    background: #1f75e5;
    text-align: center;
  }
  /deep/ .van-card {
    background-color: #eeeaea;
    .van-tag--plain {
      margin-right: 5px;
    }
    .van-card__desc {
      margin-bottom: 10px;
      font-size: 14px;
      color: #000;
    }
    .van-card__bottom {
      margin-top: 15px;
      .count {
        display: flex;
        justify-content: end;
        align-items: center;
        margin: 15px 0;
        span {
          font-size: 16px;
        }
      }
      .van-card__price {
        font-size: 24px !important;
        color: #ff6a00;
      }
      .van-card__num {
        font-weight: 600;
      }
    }
    .collect {
      display: inline-block;
      vertical-align: middle;
      text-align: center;
      width: 40px;
      span {
        display: block;
        margin-bottom: 5px;
      }
      i {
        display: block;
        font-size: 18px;
        text-align: center;
        margin-bottom: 3px;
        color: #ff6a00;
      }
    }
    .cartBtn,.buyBtn {
      height: 40px;
      width: 103px;
      line-height: 40px;
      text-align: center;
      color: #fff;
      border: 0;
    }
    .cartBtn {
      border-radius: 20px 0 0 20px;
      background: linear-gradient(90deg,#ffd01e,#ff8917);
      margin-left: 80px;
    }
    .buyBtn {
      border-radius: 0 20px 20px 0;
      background: linear-gradient(90deg,#ff6034,#ee0a24);
    }
  }

}
.van-tabs {
  margin-bottom: 50px;
  padding: 10px;
  /deep/ .van-tabs__content {
    margin-top: 25px;
    img {
      max-width: 100%!important;
      height: auto!important;
    }
    .van-grid {
      .item {
        text-align: center;
        .van-grid-item__content {
          justify-content: space-between !important;
        }
        .van-image {
          margin-bottom: 20px;
        }
        p {
          margin-bottom: 5px;
          font-size: 14px;
          &:last-of-type {
            font-size: 16px;
            span {
              &:first-of-type {
                color: red;
                margin-right: 10px;
              }
            }
          }
        }
      }
    }
  }
}
</style>